package com.fongtech.cli.admin.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.fongtech.cli.admin.service.IUserService;
import com.fongtech.cli.common.annotations.Resources;
import com.fongtech.cli.common.api.CommonPage;
import com.fongtech.cli.common.api.CommonResult;
import com.fongtech.cli.enums.AuthTypeEnum;
import com.fongtech.cli.enums.StatusEnum;
import com.fongtech.cli.framework.controller.SuperController;
import com.fongtech.cli.framework.enums.ErrorCodeEnum;
import com.fongtech.cli.framework.utils.ApiAssert;
import com.fongtech.cli.mbg.model.dto.UserDTO;
import com.fongtech.cli.mbg.model.entity.User;
import com.fongtech.cli.mbg.model.param.UserPARM;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.codec.digest.Md5Crypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 系统用户表 前端控制器
 * </p>
 *
 * @author cli
 * @since 2019-09-10
 */
@RestController
@RequestMapping("/user")
public class UserRestController extends SuperController {

    @Autowired
    private IUserService userService;

    @Resources(auth = AuthTypeEnum.AUTH)
    @ApiOperation("查询所有用户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "loginName", value = "需要检查的账号", paramType = "query"),
            @ApiImplicitParam(name = "nickname", value = "需要检查的账号", paramType = "query"),
            @ApiImplicitParam(name = "status", value = "需要检查的账号", paramType = "query")
    })
    @GetMapping
    public CommonResult<CommonPage<UserDTO>> page(@RequestParam(value = "loginName", required = false) String loginName,
                                             @RequestParam(value = "nickname", required = false) String nickname,
                                             @RequestParam(value = "status", required = false) StatusEnum status) {
        ;
        return CommonResult.success(CommonPage.restPage(
                userService.query().likeRight(StringUtils.isNotEmpty(loginName), User::getLoginName, loginName)
                        .likeRight(StringUtils.isNotEmpty(nickname), User::getNickname, nickname)
                        .eq(Objects.nonNull(status), User::getStatus, status)
                        .page(this.<User>getPage())
                        .convert(e -> e.convert(UserDTO.class))
                )
        );
    }

    @Resources(auth = AuthTypeEnum.AUTH)
    @ApiOperation("查询单个用户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户ID", required = true, paramType = "path")
    })
    @GetMapping("/{id}")
    public CommonResult<UserDTO> get(@PathVariable("id") Integer id) {
        User user = userService.getById(id);
        ApiAssert.notNull(ErrorCodeEnum.USER_NOT_FOUND, user);
        UserDTO userDTO = user.convert(UserDTO.class);
        List<Integer> roleIds = userService.getRoleIds(user.getId());
        userDTO.setRoleIds(roleIds);
        return CommonResult.success(userDTO);
    }

    @Resources(auth = AuthTypeEnum.AUTH)
    @ApiOperation("重置用户密码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户ID", required = true, paramType = "path")
    })
    @PutMapping("/{id}/password")
    public CommonResult<Void> resetPwd(@PathVariable("id") Integer id) {
        userService.resetPwd(id);
        return CommonResult.success();
    }

    @Resources(auth = AuthTypeEnum.AUTH)
    @ApiOperation("设置用户状态")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户ID", required = true, paramType = "path")
    })
    @PutMapping("/{id}/status")
    public CommonResult<Void> updateStatus(@PathVariable("id") Integer id, @RequestBody @Validated(UserPARM.Status.class) UserPARM userPARM) {
        userService.updateStatus(id, userPARM.getStatus());
        return CommonResult.success();
    }

    @Resources(auth = AuthTypeEnum.AUTH)
    @ApiOperation("创建用户")
    @PostMapping
    public CommonResult<Void> create(@RequestBody @Validated(UserPARM.Create.class) UserPARM userPARM) {
        int count = userService.query().eq(User::getLoginName, userPARM.getLoginName()).count();
        ApiAssert.isTrue(ErrorCodeEnum.USERNAME_ALREADY_EXISTS, count == 0);
        User user = userPARM.convert(User.class);
        //没设置密码 设置默认密码
        if (StringUtils.isEmpty(user.getPassword())) {
            user.setPassword(Md5Crypt.apr1Crypt(user.getLoginName(), user.getLoginName()));
        }
        //默认禁用
        user.setStatus(StatusEnum.DISABLE);
        userService.save(user);
        userService.saveUserRoles(user.getId(), userPARM.getRoleIds());
        return CommonResult.success();
    }

    @Resources(auth = AuthTypeEnum.AUTH)
    @ApiOperation("修改用户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户ID", required = true, paramType = "path")
    })
    @PutMapping("/{id}")
    public CommonResult<Void> update(@PathVariable("id") Integer id, @RequestBody @Validated(UserPARM.Update.class) UserPARM userPARM) {
        User user = userPARM.convert(User.class);
        user.setId(id);
        userService.updateById(user);
        userService.saveUserRoles(id, userPARM.getRoleIds());
        return CommonResult.success();
    }

}

